﻿/*
* Copyright 2010 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using System.Runtime.Serialization;
using Ngilead.Common;
using Ngilead.Common.Base;

namespace Ngilead.Test.Models
{
    /// <summary>
    /// Abstract base class for persistent object
    /// </summary>
    /// <typeparam name="TId">Id type</typeparam>
    [DataContract]
    public abstract class AbstractPersistentObject<TId> : LightEntity, ILightEntity, IModel
    {
        #region Private

        private TId _id;
        private Int32 _version;

        #endregion

        #region Publics

        /// <summary>
        /// Id
        /// </summary>
        [DataMember]
        public virtual TId Id
        {
            get { return _id; }
            set { _id = value; }
        }

        /// <summary>
        /// Version
        /// </summary>
        [DataMember]
        public virtual Int32 Version
        {
            get { return _version; }
            set { _version = value; }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public AbstractPersistentObject() { }

        #endregion

        #region Override

        /// <summary>
        /// Override Equals()
        /// </summary>
        public override bool Equals(object obj)
        {
            if (obj == this) return true;
            if (obj == null) return false;

            AbstractPersistentObject<TId> that = obj as AbstractPersistentObject<TId>;
            if (that == null) return false;
            if (!that.Id.Equals(this.Id)) return false;

            return true;
        }

        /// <summary>
        /// Override GetHashCode()
        /// </summary>
        public override int GetHashCode()
        {
            int hash = Id.GetHashCode();
            if (hash == 0)
                hash = this.GetType().FullName.GetHashCode() + base.GetHashCode();
            else
                hash = this.GetType().FullName.GetHashCode() + hash;
            return hash;
        }

        /// <summary>
        /// Override ToString()
        /// </summary>
        public override string ToString()
        {
            return String.Format("{0} : Id {1} - Version {2}", this.GetType().Name, Id.ToString(), Version);
        }

        #endregion
    }
}
